import React, { Component } from 'react';
import { Form, Select, Icon, Divider } from 'antd';
import ScrollSelect from '@/components/ScrollSelect';
import Range from '@/components/Range';
import isNaN from 'lodash/isNaN';
import api from '@/api';
import { PRODUCT_TYPE } from '@/Constants';
import { FormItem } from './ServiceView';
@Form.create()
export class ServiceForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showConfig: false,
      selectedService: {},
      cargoTypes: [],
      weightValid: '',
      weightHelp: '',
      currentService: {
        data: {},
      },
      regionList: [],
      prevService: [],
    };
  }
  componentDidMount() {
    const { currentNode } = this.props;
    if (currentNode.depth > 0) {
      this.setState({
        currentService: currentNode,
      });
      this.searchServiceById(currentNode.data.serviceId);
    }
    if (currentNode.parent && currentNode.parent.data && currentNode.parent.data.phaseId) {
      this.fetchPrevService(currentNode.parent.data.phaseId);
    }
    if (currentNode.data && currentNode.data.phaseId) {
      this.fetchPrevService(currentNode.data.phaseId);
    }
  }
  fetchPrevService = phaseId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/fetchPrevProduct',
      payload: {
        pathParams: {
          phaseId,
        },
      },
    }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.setState({ prevService: data });
      }
    });
  };
  componentWillReceiveProps(nextProps) {
    if (nextProps.currentNode.depth > 0 && nextProps.drawVisible && !this.props.drawVisible) {
      this.setState({
        currentService: nextProps.currentNode,
        showConfig: false,
      });
      this.searchServiceById(nextProps.currentNode.data.serviceId);
      this.fetchPrevService(nextProps.currentNode.parent.data.phaseId);
    }
  }
  searchService = params => {
    const { serviceTypeCode } = this.props;
    return api.service.queryOnline({
      queryParams: {
        serviceTypeCode,
        ...params,
      },
    });
  };
  toggleConfig = () => {
    this.setState({
      showConfig: !this.state.showConfig,
    });
  };
  composeCargoType = (codeList, nameList) => {
    return codeList.map((item, index) => ({ code: item, name: nameList[index] }));
  };
  searchServiceById = async id => {
    let res = await api.service.queryById({
      pathParams: {
        id,
      },
    });
    if (res.errorCode === 0) {
      this.setState({
        selectedService: res.data,
        cargoTypes: this.composeCargoType(res.data.cargoTypeCodeList, res.data.cargoTypeNameList),
        weightHelp: res.data.weightLimitMin
          ? `所选服务的重量区间[${res.data.weightLimitMin}-${res.data.weightLimitMax}]${
          res.data.weightLimitUnitCode
          }`
          : '',
        weightValid: res.data.weightLimitMin ? 'validating' : '',
        regionList: res.data.regionItemRelationList
      });
    }
  };
  handleChangeService = service => {
    this.searchServiceById(service.key);
    this.setState({
      currentService: { data: {} },
      showConfig: false,
    });
  };
  checkWeight = (rule, value, callback) => {
    const { selectedService } = this.state;
    let { start = '', end = '' } = value;
    try {
      start = parseFloat(start);
      end = parseFloat(end);
      if (isNaN(start) && isNaN(end)) {
        this.setState({
          weightValid: 'validating',
        });
        return callback();
      }
      if (selectedService.weightLimitMin && selectedService.weightLimitMax) {
        if (
          end > start &&
          start >= selectedService.weightLimitMin &&
          end <= selectedService.weightLimitMax
        ) {
          this.setState({
            weightValid: 'validating',
          });
        } else {
          this.setState({
            weightValid: 'error',
          });
          return callback(rule.message);
        }
      } else {
        if (end > start) {
          this.setState({
            weightValid: 'validating',
          });
        } else {
          this.setState({
            weightValid: 'error',
          });
          return callback(rule.message);
        }
      }
      callback();
    } catch (error) {
      if (typeof start !== 'number' && typeof end !== 'number') {
        this.setState({
          weightValid: 'validating',
        });
      } else {
        this.setState({
          weightValid: 'error',
        });
        return callback(rule.message);
      }
      callback();
    }
  };
  render() {
    const { form, currentNode, ratings, drawVisible, currentProduct } = this.props;
    const {
      showConfig,
      cargoTypes,
      weightValid,
      weightHelp,
      currentService,
      selectedService,
      prevService,
      regionList
    } = this.state;
    let isFirst =
      (currentNode.parent && currentNode.parent.data.ordinal === 1) ||
      currentNode.data.ordinal === 1;
    return (
      <div>
        {drawVisible && (
          <FormItem label="服务名称" labelCol={{ span: 5 }} wrapperCol={{ span: 17 }}>
            {form.getFieldDecorator('serviceId', {
              rules: [{ required: true, message: '服务名称不能为空' }],
              initialValue: {
                key: currentService.data.serviceId,
                label: currentService.data.serviceName,
              },
            })(
              <ScrollSelect
                style={{ width: 300 }}
                search={this.searchService}
                optionKey="id"
                filterOption={false}
                onChange={this.handleChangeService}
                disabled={currentService.data.serviceId}
              />
            )}
          </FormItem>
        )}
        {form.getFieldValue('serviceId') && (
          <Divider orientation="right">
            <span style={{ cursor: 'pointer' }} onClick={this.toggleConfig}>
              分配条件 <Icon type={showConfig ? 'down-circle' : 'up-circle'} />
            </span>
          </Divider>
        )}
        {showConfig && (
          <>
            {regionList.length > 0 && (
              <FormItem
                label='服务范围'
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 17 }}
              >
                {form.getFieldDecorator('regionItemIdListOfStart', {
                  initialValue: currentService.data.regionItemIdListOfStart,
                })(
                  <Select style={{ width: 300 }} mode="multiple">
                    {regionList.map((item, index) => (
                      <Option key={index} value={item.id}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            )}
            {!isFirst && (
              <FormItem label="上游服务" labelCol={{ span: 5 }} wrapperCol={{ span: 17 }}>
                {form.getFieldDecorator('previousServiceList', {
                  initialValue: currentService.data.previousServiceList,
                })(
                  <Select style={{ width: 300 }} mode="multiple">
                    {prevService.map((service, index) => (
                      <Option key={index} value={service.id}>
                        {service.serviceName}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            )}
            <FormItem label="货物类型" labelCol={{ span: 5 }} wrapperCol={{ span: 17 }}>
              {form.getFieldDecorator('cargoTypeCodeList', {
                initialValue: currentService.data.cargoTypeCodeList,
              })(
                <Select style={{ width: 300 }} mode="multiple">
                  {cargoTypes.map((cargoType, index) => (
                    <Option key={index} value={cargoType.code}>
                      {cargoType.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <FormItem
              label="重量限制"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 17 }}
              help={weightHelp}
              validateStatus={weightValid}
            >
              {form.getFieldDecorator('weightLimit', {
                rules: [{ validator: this.checkWeight, message: weightHelp }],
                initialValue: {
                  start: currentService.data.weightLimitMin,
                  end: currentService.data.weightLimitMax,
                },
              })(
                <Range
                  max={99999}
                  min={0}
                  precision={3}
                  extra={<span style={{ marginLeft: 10 }}>kg</span>}
                />
              )}
            </FormItem>
            <FormItem label="客户等级" labelCol={{ span: 5 }} wrapperCol={{ span: 17 }}>
              {form.getFieldDecorator('customerLevel', {
                initialValue: currentService.data.customerLevel,
              })(
                <Select
                  allowClear
                  showSearch
                  optionFilterProp="children"
                  style={{ width: 140, marginRight: 20 }}
                >
                  {ratings.map(val => (
                    <Option key={val.id} value={val.id}>{`${val.name}`}</Option>
                  ))}
                </Select>
              )}
              {form.getFieldDecorator('customerLevelExt', {
                initialValue: currentService.data.customerLevelExt,
              })(
                <Select allowClear optionFilterProp="children" style={{ width: 140 }}>
                  <Option value="MORE">及以上</Option>
                  <Option value="LESS">及以下</Option>
                </Select>
              )}
            </FormItem>
            <FormItem label="申报价值" labelCol={{ span: 5 }} wrapperCol={{ span: 17 }}>
              {form.getFieldDecorator('declaredValue', {
                rules: [{ validator: Range.validate, message: '下限必须小于上限' }],
                initialValue: {
                  start: currentService.data.declaredValueMin,
                  end: currentService.data.declaredValueMax,
                },
              })(
                <Range
                  max={99999}
                  min={0}
                  precision={3}
                  extra={
                    <span style={{ marginLeft: 10 }}>
                      {currentProduct.productGroup === PRODUCT_TYPE.CROSS ? 'USD' : 'CNY'}
                    </span>
                  }
                />
              )}
            </FormItem>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} label="单量">
              {form.getFieldDecorator('orderQuantity', {
                initialValue: currentService.data.orderQuantity,
              })(
                <Select allowClear optionFilterProp="children" style={{ width: 300 }}>
                  <Option value={0.1}>10%</Option>
                  <Option value={0.2}>20%</Option>
                  <Option value={0.3}>30%</Option>
                  <Option value={0.4}>40%</Option>
                  <Option value={0.5}>50%</Option>
                  <Option value={0.6}>60%</Option>
                  <Option value={0.7}>70%</Option>
                  <Option value={0.8}>80%</Option>
                  <Option value={0.9}>90%</Option>
                  <Option value={1.0}>100%</Option>
                </Select>
              )}
            </FormItem>
          </>
        )}
      </div>
    );
  }
}
